<?php

namespace app\api\controller;

use app\admin\model\UserOne;
use app\admin\model\UserThree;
use app\admin\model\UserTwo;
use app\api\BaseController;
use app\api\middleware\Auth;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Db;
use app\common\controller\Sms;

/**
 * 登陆注册
 */
class Login extends BaseController
{
    protected $middleware = [
        Auth::class => ['except' 	=> ['wxPhone','getOpenid','xieyi','phoneLogin','phoneTwoLogin','phoneThreeLogin','getAccessToken','sendCode'] ]
    ];

    /**
     * 用户服务协议,服务范围
     */
    public function xieyi()
    {
        $data = Db::name('config')->where('id',8)->find();
        $conf = unserialize($data['content']);
        $conf['fuwu'] = str_replace('src="/storage','src="'.request()->domain().'/storage',$conf['fuwu']);

        $setting = Db::name('config')->where('id',10)->find();
        $set = unserialize($setting['content']);
        $return = [
            'use_xieyi' => $conf['fuwu'],
            'ys_xieyi' => $conf['ys_xieyi'],
            'ban' => $set['ban'],
            'bg_img_login' => $set['bg_img_login'],
        ];
        return success('',$return);
    }

    /**
     * 手机号密码登录(售酒端)
     */
    public function phoneLogin()
    {
        if (request()->isPost()) {
            $param = get_params();
            if (empty($param['mobile']) || empty($param['password'])) {
                return error('手机号和密码不能为空');
            }
            $user = Db::name('user_one')->where([['mobile','=',$param['mobile']],['password','=',$param['password']]])->find();
            if (empty($user)) {
                return error('手机号或密码错误');
            }
            if (empty($user['openid'])) {
                if (empty($param['code'])) {
                    return error('code参数不能为空');
                }
                $res = $this->getOpenid($param['code'],1);
                $res = json_decode($res,true);
                if (!empty($res['code'])) {
                    return error('登录失败,授权获取openid失败');
                }
                Db::name('user_one')->where('id',$user['id'])->update(['openid'=>$res['data']]);
            }
            $index = new Index();
            $token = $index->getToken($user['id']);
            return json(['code'=>0,'msg'=>'登录成功','data'=>$user,'token'=>$token]);
        }
    }


    /**
     * 获取openid
     */
    public function getOpenid($code,$type)
    {
        if ($type == 1) {
            $appid = config('config.wechat_one.appid');
            $appSecret = config('config.wechat_one.app_secret');
        } elseif ($type == 2) {
            $appid = config('config.wechat_two.appid');
            $appSecret = config('config.wechat_two.app_secret');
        } else {
            $appid = config('config.wechat_three.appid');
            $appSecret = config('config.wechat_three.app_secret');
        }
        //获取openid
        $curlUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appSecret."&js_code=".$code."&grant_type=authorization_code";
        $results = curl_get($curlUrl);
        $openidResult = json_decode($results,true);
        if (empty($openidResult['openid'])) {
            return json_encode(['code'=>1,'msg'=>'appId参数错误'],JSON_UNESCAPED_UNICODE);
        }
        return json_encode(['code'=>0,'msg'=>'success','data'=>$openidResult['openid']],JSON_UNESCAPED_UNICODE);
    }

    /**
     * 手机号密码登录(售酒机管理员)
     */
    public function phoneTwoLogin()
    {
        if (request()->isPost()) {
            $param = get_params();
            if (empty($param['mobile']) || empty($param['password'])) {
                return error('手机号和密码不能为空');
            }
            $user = Db::name('user_two')->where([['mobile','=',$param['mobile']],['password','=',$param['password']]])->find();
            if (empty($user)) {
                return error('手机号或密码错误');
            }
            if (empty($user['openid'])) {
                if (empty($param['code'])) {
                    return error('code参数不能为空');
                }
                $res = $this->getOpenid($param['code'],2);
                $res = json_decode($res,true);
                if (!empty($res['code'])) {
                    return error('登录失败,授权获取openid失败');
                }
                Db::name('user_two')->where('id',$user['id'])->update(['openid'=>$res['data']]);
            }
            $index = new Index();
            $token = $index->getToken($user['id']);
            return json(['code'=>0,'msg'=>'登录成功','data'=>$user,'token'=>$token]);
        }
    }

    /**
     * 手机号密码登录(补酒员)
     */
    public function phoneThreeLogin()
    {
        if (request()->isPost()) {
            $param = get_params();
            if (empty($param['mobile']) || empty($param['password'])) {
                return error('手机号和密码不能为空');
            }
            $user = Db::name('user_three')->where([['mobile','=',$param['mobile']],['password','=',$param['password']]])->find();
            if (empty($user)) {
                return error('手机号或密码错误');
            }
            if (empty($user['openid'])) {
                if (empty($param['code'])) {
                    return error('code参数不能为空');
                }
                $res = $this->getOpenid($param['code'],3);
                $res = json_decode($res,true);
                if (!empty($res['code'])) {
                    return error('登录失败,授权获取openid失败');
                }
                Db::name('user_three')->where('id',$user['id'])->update(['openid'=>$res['data']]);
            }
            $index = new Index();
            $token = $index->getToken($user['id']);
            return json(['code'=>0,'msg'=>'登录成功','data'=>$user,'token'=>$token]);
        }
    }

    /**
     * 获取用户信息(售酒端)
     */
    public function userOneInfo()
    {
        $user = Db::name('user_one')->where('id',JWT_UID)->find();
        //待结算
        $user['wallet_dai'] = Db::name('wallet_log')
            ->where(['uid'=>$user['id'],'user_type'=>1,'status'=>0,'delete_time'=>0])->sum('num');
        return success('获取成功',$user);
    }

    /**
     * 获取用户信息(售酒机管理员)
     */
    public function userTwoInfo()
    {
        $user = Db::name('user_two')->where('id',JWT_UID)->find();
        //待结算
        $user['wallet_dai'] = Db::name('wallet_log')
            ->where(['uid'=>$user['id'],'user_type'=>2,'status'=>0,'delete_time'=>0])->sum('num');
        return success('获取成功',$user);
    }

    /**
     * 获取用户信息(售酒机管理员)
     */
    public function userThreeInfo()
    {
        $user = Db::name('user_three')->where('id',JWT_UID)->find();
        //待结算
        $user['wallet_dai'] = Db::name('wallet_log')
            ->where(['uid'=>$user['id'],'user_type'=>3,'status'=>0,'delete_time'=>0])->sum('num');
        return success('获取成功',$user);
    }

    /**
     * 修改用户信息(售酒端)
     */
    public function editUserOne()
    {
        $param = get_params();
        $param['update_time'] = time();
        UserOne::update($param,['id'=>JWT_UID]);
        return success('修改成功');
    }

    /**
     * 修改用户信息(用户端)
     */
    public function editUser()
    {
        $param = get_params();
        $param['update_time'] = time();
//        if (empty($param['avatar'])) {
//            unset($param['avatar']);
//        }
//        if (empty($param['nickname'])) {
//            unset($param['nickname']);
//        }
//        if (empty($param['mobile'])) {
//            unset($param['mobile']);
//        }
        $user = Db::name('user')->where('id',JWT_UID)->find();
        if (!empty($user['user_type']) && ($user['user_type'] == 2) && !empty($param['company_logo'])) {
            if (!empty($param['company'])) {
                $param['nickname'] = $param['company'];
            }
            $param['avatar'] = $param['company_logo'];
        }
        if (!empty($user['user_type']) && ($user['user_type'] == 2) && !empty($param['avatar'])) {
            if (!empty($param['company'])) {
                $param['nickname'] = $param['company'];
            }
            $param['company_logo'] = $param['avatar'];
        }
        \app\admin\model\User::update($param,['id'=>JWT_UID]);
        return success('修改成功');
    }

    /**
     * 修改用户信息(售酒机管理员)
     */
    public function editUserTwo()
    {
        $param = get_params();
        $param['update_time'] = time();
        UserTwo::update($param,['id'=>JWT_UID]);
        return success('修改成功');
    }

    /**
     * 修改用户信息(补酒员)
     */
    public function editUserThree()
    {
        $param = get_params();
        $param['update_time'] = time();
        UserThree::update($param,['id'=>JWT_UID]);
        return success('修改成功');
    }

    /**
     * 手机号授权登陆
     */
    public function wxPhone()
    {
        if (request()->isPost()) {
            $param = request()->param();
            if (empty($param['l_code'])) {
                return json(['code'=>1,'msg'=>'code参数为空']);
            }
            $appid = config('config.wechat.appid');
            $appSecret = config('config.wechat.app_secret');
//            $token = $this->getAccessToken($appid,$appSecret);
//            $token = json_decode($token,true);
//            $access_token = $token['access_token'];

            //获取openid
            $curlUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appSecret."&js_code=".$param['l_code']."&grant_type=authorization_code";
            $results = curl_get($curlUrl);
            $openidResult = json_decode($results,true);
            if (empty($openidResult['openid'])) {
                return json(['code'=>1,'msg'=>'appId参数错误']);
            }
            $user = Db::name('user')->where(['openid'=>$openidResult['openid']])->find();
            $index = new Index();
            if (!empty($user)) {
                $token = $index->getToken($user['id']);
                $user['is_first'] = 0;
                return json(['code'=>0,'msg'=>'登录成功','data'=>$user,'token'=>$token]);
            }
            //获取手机号
//            $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$access_token;
//            $res = curl_post($url,json_encode(['code'=>$param['code']]));
//            $result = json_decode($res,true);
//
//            if (!empty($result['errcode'])) {
//                return json(['code'=>1,'msg'=>'手机号授权失败']);
//            }

            //随机获取用户昵称
            $add = [
                'nickname' => '用户'.get_random_str(5,3),
                'avatar' => '/static/admin/images/logo.png',
                'openid' => $openidResult['openid'],
                'register_time' => time()
            ];
            if (!empty($param['pid'])) {
                $add['pid'] = $param['pid'];
            }
            $uid = Db::name('user')->insertGetId($add);
            $user = Db::name('user')->where('id',$uid)->find();
            $user['is_first'] = 1;
            $token = $index->getToken($user['id']);
            return json(['code'=>0,'msg'=>'登录成功','data'=>$user,'token'=>$token]);
        }
    }

    public function getAccessToken($appid,$appSecret)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appSecret;
        $result = curl_get($url);
        return $result;
    }

    /**
     * 获取用户信息
     */
    public function userInfo()
    {
        $user = Db::name('user')->where('id',JWT_UID)->find();
        $user['mobiles'] = '';
        $user['level_name'] = '';
        if (empty($user['mobile'])) {
            $user['mobile'] = '';
        } else {
            $user['mobiles'] = substr_replace($user['mobile'],'****',3,4);
        }
        if (!empty($user['level'])) {
            $user['level_name'] = Db::name('user_level')->where('id',$user['level'])->value('title');
        }
        $nums = 0;
        $nums1 = 0;
        $nums2 = 0;

        if ($user['user_type'] == 1) {
            $user_type = '个人';
        } else {
            $user_type = '企业';
        }
        $start = strtotime(date('Y-m-d'));
        $end = strtotime(date('Y-m-d 23:59:59'));
        if (!empty($user['is_svip_one'])) {
            $read = Db::name('user_level')->where('id',2)->value('read');
            $nums += $read;
            $nums1 += $read;
        }
        if (!empty($user['is_svip_two'])) {
            $read = Db::name('user_level')->where('id',4)->value('read');
            $nums += $read;
            $nums1 += $read;
        }
        if (!empty($user['is_vip_one'])) {
            $read = Db::name('user_level')->where('id',1)->value('read');
            $nums += $read;
            $nums2 += $read;
        }
        if (!empty($user['is_vip_two'])) {
            $read = Db::name('user_level')->where('id',3)->value('read');
            $nums += $read;
            $nums2 += $read;
        }
        //今日已用
        $count1 = Db::name('news_sel')
            ->where([['create_time','between',[$start,$end]],['news_file_id','>',0],['uid','=',JWT_UID]])
            ->count();
        $count2 = Db::name('news_sel')
            ->where([['create_time','between',[$start,$end]],['news_file_id','=',0],['uid','=',JWT_UID]])
            ->count();
        $user['nums'] = $nums;

        if (!empty($user['is_vip_one']) || !empty($user['is_vip_two'])) {
            $user['vip_title'] = 'VIP可解锁额度:'.$count2.'/'.$nums2.'条';
        } else {
            $user['vip_title'] = '';
        }
        if (!empty($user['is_svip_one']) || !empty($user['is_svip_two'])) {
            $user['svip_title'] = 'SVIP可解锁额度:'.$count1.'/'.$nums1.'条';
        } else {
            $user['svip_title'] = '';
        }
         $user['hai_title'] = $user['hai_titlevip'];

        //今日查看次数
        $start = strtotime(date('Y-m-d'));
        $end = strtotime(date('Y-m-d 23:59:59'));
        $count = Db::name('news_sel')->where([['create_time','between',[$start,$end]],['uid','=',$user['id']]])->count();

        $user['after_nums'] = $nums - $count;
        return success('获取成功',$user);
    }

    /**
     * 绑定手机号
     */
    public function bindMobile()
    {
        if (request()->isPost()) {
            $param = get_params();
            if (empty($param['mobile']) || empty($param['code'])) {
                return error('手机号和验证码不能为空');
            }
            //验证码校验
            $code = cache('register_code_'.$param['mobile']);
            if ($code != $param['code']) {
                return json(['code'=>1,'msg'=>'验证码错误']);
            }
            cache('register_code_'.$param['mobile'],null);
            $user = Db::name('user')->where('id',JWT_UID)->find();
            if (!empty($user['mobile'])) {
                return error('当前账号已绑定手机号');
            }
            $isBind = Db::name('user')->where('mobile',$param['mobile'])->find();
            if (!empty($isBind)) {
                return error('当前手机号已注册');
            }
            Db::name('user')->where('id',$user['id'])->update(['mobile'=>$param['mobile']]);
            return success('绑定成功');
        }
    }

    /**
     * 发送短信验证的接口
     */
    public function sendCode()
    {
        if (request()->isPost()) {
            $phone = request()->param('mobile');
            // 生成4位到6位的随机数
            $begin_time=time();
            $last_time=Cache::get('register_time_'.$phone);
            if ($begin_time - $last_time < 60){
                $res = [
                    'code'=>1,
                    'msg' => '请求次数太多',
                ];
                return json($res);
            }
            $code = mt_rand(1111,9999);
            $sms = new Sms();
            $result = $sms->send_verify($phone,$code);

            if ($result){
//            发送成功
//            验证码时间限制，单位时间过期
                Cache::set('register_code_'.$phone,$code,60);
                Cache::set('register_time_'.$phone,time());
                $res=[
                    'code' =>0,
                    'msg' =>'短信发送成功',
                    'data'=>$code
                ];
            }else{
                $res=[
                    'code'=>1,
                    'msg'=>'短信发送失败',
                    'data'=>$code
                ];
            }
            return json($res);
        }
    }
}